//
//  LoginController.m
//  MyAppTest
//
//  Created by Sunshine on 2018/7/11.
//  Copyright © 2018年 Sunshine. All rights reserved.
//

#import "LoginController.h"
#import "RegistController.h"
#import "ForgotPassCon.h"


#import "WXApi.h"
#import "AppDelegate.h"
//微信开发者ID
#define URL_APPID @"wx5160f8411c9f33ea"
#define URL_SECRET @"ea8489b1810a14ff9c30292e6cb360f6"
#import "AFNetworking.h"

@interface LoginController ()<WXDelegate,UITextFieldDelegate>

{
    AppDelegate *appdelegate;
    
}

@property(nonatomic,strong)UIView *backview;
@property(nonatomic,strong)NSString *yzmStr;
@property(nonatomic,strong)UITextField *yzmphonefi;
@property(nonatomic,strong)UITextField *yzmfield;
@property(nonatomic,strong)UIImageView *titimagevi;


@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
     NSString *urlstr = [MethodClass returnUrlSetStrWSDLURL:@"/dashop/advertise/app/advertisePic.do?ADV_FLAG=DLZC1"];
    [self imageDataMethodWithUrl:urlstr];
    [self creatViewMethod];
}
//文章列表
-(void)imageDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSArray *arr = response;
        if (arr.count > 0) {
            NSDictionary *dic = arr[0];
            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                NSString *urlstr = [MethodClass returnUrlSetStrWSDLURL:dic[@"ADVERTISE_PIC"]];
                [self.titimagevi sd_setImageWithURL:[NSURL URLWithString:urlstr]];
            }];
        }
    } failBlock:^(NSError *error) {
        
    }];
    
}
-(void)creatViewMethod{
    self.view.backgroundColor = LineBackColor;
    UIImageView *titimageview = [UIImageView new];
    self.titimagevi = titimageview;
    titimageview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titimageview];
    titimageview.sd_layout
    .topSpaceToView(self.view, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .heightIs(200*kJLXWidthScale);
    
    NSInteger height;
    if (kScreenWidth == 320) {
        height = 45*kJLXWidthScale;
    }else{
        height = 50*kJLXWidthScale;
    }
    
    for (int i = 0; i < 2; i ++) {
        UIView *fieldview = [UIView new];
        fieldview.backgroundColor = [UIColor whiteColor];
        fieldview.layer.masksToBounds = YES;
        fieldview.layer.cornerRadius = 5*kJLXWidthScale;
        [self.view addSubview:fieldview];
        fieldview.sd_layout
        .topSpaceToView(titimageview, 40*kJLXWidthScale + (height + 2)*kJLXWidthScale*i)
        .leftSpaceToView(self.view, 20*kJLXWidthScale)
        .rightSpaceToView(self.view, 20*kJLXWidthScale)
        .heightIs(height);
        
        UITextField *field = [UITextField new];
        field.autocapitalizationType = UITextAutocapitalizationTypeNone;
        field.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
        [fieldview addSubview:field];
        field.sd_layout
        .topSpaceToView(fieldview, 0)
        .bottomSpaceToView(fieldview, 0)
        .rightSpaceToView(fieldview, 10*kJLXWidthScale)
        .leftSpaceToView(fieldview, 10*kJLXWidthScale);
        if (i == 0) {
            NSString *userstr = [UserDefault objectForKey:LogUserName];
            if (userstr && userstr.length > 0) {
                field.text = userstr;
            }
            field.placeholder = @"请输入用户名/手机号";
            self.phfield = field;
        }else if (i == 1){
            NSString *pastr = [UserDefault objectForKey:LogPassWord];
            if (pastr && pastr.length > 0) {
                field.text = pastr;
            }
            field.placeholder = @"请输入密码";
            field.secureTextEntry = YES;
            self.psfield = field;
        }
    }
    
    UIButton *forbtn = [UIButton buttonWithType:UIButtonTypeSystem];
    forbtn.titleLabel.font = [UIFont systemFontOfSize:14*kJLXWidthScale];
    [forbtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forbtn setTitleColor:BackColor forState:UIControlStateNormal];
    [forbtn addTarget:self action:@selector(forgotButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forbtn];
    forbtn.sd_layout
    .topSpaceToView(titimageview, 45*kJLXWidthScale + (height + 2)*kJLXWidthScale*2)
    .rightSpaceToView(self.view, 20*kJLXWidthScale)
    .heightIs(30*kJLXWidthScale)
    .widthIs(100*kJLXWidthScale);
    
    
    for (int i = 0; i < 2; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        if (i == 0) {
            btn.layer.masksToBounds = YES;
            btn.layer.cornerRadius = 8*kJLXWidthScale;
            btn.backgroundColor = [UIColor orangeColor];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitle:@"登 录" forState:UIControlStateNormal];
        }else{
            [btn setTitle:@"没有账户？注册" forState:UIControlStateNormal];
        }
        btn.tag = 500 + i;
        [btn addTarget:self action:@selector(registerAndLogButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:18*kJLXWidthScale];
        [self.view addSubview:btn];
        btn.sd_layout
        .topSpaceToView(titimageview, 80*kJLXWidthScale + (height + 2)*kJLXWidthScale*2 + 50*kJLXWidthScale*i)
        .centerXEqualToView(self.view)
        .heightIs(45*kJLXWidthScale)
        .leftSpaceToView(self.view, 20*kJLXWidthScale)
        .rightSpaceToView(self.view, 20*kJLXWidthScale);
    }
    
    
    
    MineButton *wxbtn = [MineButton buttonWithType:UIButtonTypeCustom];
    [wxbtn addTarget:self action:@selector(weixinButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wxbtn];
    wxbtn.sd_layout
    .topSpaceToView(titimageview, 300*kJLXWidthScale)
    .centerXEqualToView(self.view)
    .heightIs(70*kJLXWidthScale)
    .widthIs(50*kJLXWidthScale);
    
    wxbtn.mineimagevi = [UIImageView new];
    wxbtn.mineimagevi.image = [UIImage imageNamed:@"wechat.png"];
    [wxbtn addSubview:wxbtn.mineimagevi];
    wxbtn.mineimagevi.sd_layout
    .topSpaceToView(wxbtn, 0)
    .centerXEqualToView(wxbtn)
    .heightIs(50*kJLXWidthScale)
    .widthIs(50*kJLXWidthScale);
    
    wxbtn.minlab = [UILabel new];
    wxbtn.minlab.text = @"微信";
    wxbtn.minlab.textAlignment = NSTextAlignmentCenter;
    wxbtn.minlab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
    [wxbtn addSubview:wxbtn.minlab];
    wxbtn.minlab.sd_layout
    .topSpaceToView(wxbtn.mineimagevi, 0)
    .centerXEqualToView(wxbtn)
    .heightIs(20*kJLXWidthScale)
    .widthIs(50*kJLXWidthScale);
    
    if ([WXApi isWXAppInstalled]) {
        wxbtn.hidden = NO;
    }else{
        wxbtn.hidden = YES;
    }
    
    
    
    
}

-(void)forgotButtonAction:(UIButton *)sender{
    ForgotPassCon *forVC = [[ForgotPassCon alloc]init];
    forVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:forVC animated:YES];
}

-(void)weixinButtonAction:(MineButton *)sender{
    
//    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo";
        req.openID = URL_APPID;
        req.state = @"1245";
        appdelegate = [UIApplication sharedApplication].delegate;
        appdelegate.wxDelegate = self;
        
        [WXApi sendReq:req completion:nil];
//    }else{
//        //把微信登录的按钮隐藏掉。
//    }
    
}




#pragma mark 微信登录回调。
-(void)loginSuccessByCode:(NSString *)code{
    NSLog(@"code %@",code);
    __weak typeof(*&self) weakSelf = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil];
    //通过 appid  secret 认证code . 来发送获取 access_token的请求
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",URL_APPID,URL_SECRET,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token，然后根据access_token获取用户信息请求。
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString *jsonstr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"dic %@",dic);
        
        /*
         access_token    接口调用凭证
         expires_in    access_token接口调用凭证超时时间，单位（秒）
         refresh_token    用户刷新access_token
         openid    授权用户唯一标识
         scope    用户授权的作用域，使用逗号（,）分隔
         unionid     当且仅当该移动应用已获得该用户的userinfo授权时，才会出现该字段
         */
        NSString* accessToken=[dic valueForKey:@"access_token"];
        NSString* openID=[dic valueForKey:@"openid"];
        [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %@",error.localizedFailureReason);
    }];
    
}

-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //开发人员拿到相关微信用户信息后， 需要与后台对接，进行登录
        NSString *urlstr = [NSString stringWithFormat:@"/dashop/happuser/app/otherlogin.do?OPEN_ID=%@&NAME=%@&SFID=%@&SEX=%@",dic[@"openid"],dic[@"nickname"],dic[@"headimgurl"],dic[@"sex"]];
        NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
        NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [self weixinRequestData:newUrlString];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %ld",(long)error.code);
    }];
}

-(void)weixinRequestData:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            if ([response[@"RESULT"] integerValue] == 1) {
                NSDictionary *dic = response[@"APPUSER"];
//                NSString *phone = dic[@"PHONE"];
                NSString *phone = @"1000";
                if (phone && phone.length > 0) {
                    [UserDefault setObject:self.phfield.text forKey:LogUserName];
                    [UserDefault setObject:self.psfield.text forKey:LogPassWord];
                    [UserDefault setObject:dic[@"NAME"] forKey:LogRealName];
                    [UserDefault setObject:dic[@"USER_ID"] forKey:LogUserID];
                    [UserDefault setObject:dic[@"SFID"] forKey:LogUserSFID];
                    self.logBlock(response[@"APPUSER"]);
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    if (!self.backview) {
                        self.backview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                        self.backview.userInteractionEnabled = YES;
                        self.backview.backgroundColor = [[UIColor lightGrayColor]colorWithAlphaComponent:0.5];
                        [self.view.window addSubview:self.backview];
                        UIView *phview = [UIView new];
                        phview.layer.masksToBounds = YES;
                        phview.layer.cornerRadius = 8*kJLXWidthScale;
                        phview.backgroundColor = [UIColor whiteColor];
                        [self.backview addSubview:phview];
                        phview.sd_layout
                        .centerXEqualToView(self.backview)
                        .centerYEqualToView(self.backview)
                        .heightIs(200*kJLXWidthScale)
                        .widthIs(kScreenWidth - 80*kJLXWidthScale);

                        UILabel *titlab = [UILabel new];
                        titlab.text = @"请验证手机号";
                        titlab.textAlignment = NSTextAlignmentCenter;
                        titlab.textColor = [UIColor blackColor];
                        titlab.font = [UIFont systemFontOfSize:17*kJLXWidthScale];
                        [phview addSubview:titlab];
                        titlab.sd_layout
                        .topSpaceToView(phview, 5*kJLXWidthScale)
                        .leftSpaceToView(phview, 0)
                        .rightSpaceToView(phview, 0)
                        .heightIs(30*kJLXWidthScale);


                        for (int i = 0; i < 2; i ++) {
                            UITextField *field = [UITextField new];
                            field.delegate = self;
                            field.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
                            [phview addSubview:field];
                            if (i == 0) {
                                field.sd_layout
                                .topSpaceToView(titlab, i*50*kJLXWidthScale)
                                .rightSpaceToView(phview, 10*kJLXWidthScale)
                                .leftSpaceToView(phview, 10*kJLXWidthScale)
                                .heightIs(50*kJLXWidthScale);
                                field.placeholder = @"手机号";
                                self.yzmphonefi = field;
                            }else if(i == 1){
                                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                                btn.backgroundColor = [UIColor lightGrayColor];
                                btn.layer.masksToBounds = YES;
                                btn.layer.cornerRadius = 10*kJLXWidthScale;
                                [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
                                [btn addTarget:self action:@selector(yzmButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                                btn.titleLabel.font = [UIFont systemFontOfSize:15*kJLXWidthScale];
                                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                [phview addSubview:btn];
                                btn.sd_layout
                                .topSpaceToView(titlab, i*55*kJLXWidthScale)
                                .heightIs(40*kJLXWidthScale)
                                .rightSpaceToView(phview, 20*kJLXWidthScale)
                                .widthIs(110*kJLXWidthScale);
                                field.placeholder = @"输入验证码";
                                field.sd_layout
                                .topSpaceToView(titlab, 50*kJLXWidthScale)
                                .heightIs(50*kJLXWidthScale)
                                .rightSpaceToView(btn, 10*kJLXWidthScale)
                                .leftSpaceToView(phview, 10*kJLXWidthScale);
                                self.yzmfield = field;
                            }

                        }

                        NSArray *arr = @[@"取消",@"确定"];
                        for (int i = 0; i < 2; i ++) {
                            UIView *btnview = [UIView new];
                            btnview.userInteractionEnabled = YES;
                            [phview addSubview:btnview];
                            btnview.sd_layout
                            .bottomSpaceToView(phview, 10*kJLXWidthScale)
                            .leftSpaceToView(phview, phview.width/2*i)
                            .widthIs(phview.width/2)
                            .heightIs(50*kJLXWidthScale);

                            MineButton *btn = [MineButton buttonWithType:UIButtonTypeCustom];
                            btn.usinfo = dic;
                            btn.tag = 600 + i;
                            btn.layer.masksToBounds = YES;
                            btn.layer.cornerRadius = 5*kJLXWidthScale;
                            btn.layer.borderColor = [UIColor orangeColor].CGColor;
                            btn.layer.borderWidth = 1;
                            [btn addTarget:self action:@selector(phButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                            [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
                            [btn setTitle:arr[i] forState:UIControlStateNormal];
                            [btnview addSubview:btn];
                            btn.sd_layout
                            .centerXEqualToView(btnview)
                            .centerYEqualToView(btnview)
                            .heightIs(35*kJLXWidthScale)
                            .widthIs(btnview.width - 40*kJLXWidthScale);
                        }

                    }else{
                        self.backview.hidden = NO;
                    }
                }
            }else{
                [self alerWithMessage:response[@"MESSAGE"]];
            }
            [UserDefault synchronize];
        }];
        
        
    } failBlock:^(NSError *error) {
        
    }];
}

-(void)yzmButtonAction:(UIButton *)sender{
    
    if (self.yzmphonefi.text.length == 0) {
        [self alerWithMessage:@"手机号不能为空"];
    }else{
        if(![MethodClass utilityCheckPhoneNumInput:self.yzmphonefi.text]) {
            [self alerWithMessage:@"输入正确的手机号"];
            self.yzmphonefi.text = @"";
        }else{
            NSString *urlstr = [NSString stringWithFormat:@"/dashop/sms/app/sendsms.do?PHONE=%@",self.yzmphonefi.text];
            NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
            [self YZMMethodWithUrl:endstr];
            NSInteger num = 60;
            [MethodClass verificationCode:num blockYes:^{
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
            } blockNo:^(id time) {
                [sender setTitle:time forState:UIControlStateNormal];
            }];
            
        }
    }
    
    
}

-(void)YZMMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        self.yzmStr = dic[@"STATUSCODE"];
    } failBlock:^(NSError *error) {
        
    }];
}

-(void)phButtonAction:(MineButton *)sender{
    if (sender.tag == 600) {
        self.backview.hidden = YES;
        self.yzmStr = @"";
    }else{
        self.backview.hidden = YES;
        [UserDefault setObject:self.phfield.text forKey:LogUserName];
        [UserDefault setObject:self.psfield.text forKey:LogPassWord];
        [UserDefault setObject:sender.usinfo[@"NAME"] forKey:LogRealName];
        [UserDefault setObject:sender.usinfo[@"USER_ID"] forKey:LogUserID];
        [UserDefault setObject:sender.usinfo[@"SFID"] forKey:LogUserSFID];
        self.logBlock(sender.usinfo);
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(void)registerAndLogButtonAction:(UIButton *)sender{
    if (sender.tag - 500 == 0) {
        if (self.phfield.text == nil || self.phfield.text.length == 0) {
            [self alerWithMessage:@"请输入用户名或手机号"];
        }else if (self.psfield.text == nil || self.psfield.text.length == 0){
            [self alerWithMessage:@"请输入密码"];
        }else{
            [self loginRequestMethod];
        }
    }else{
        RegistController *regVC = [[RegistController alloc]init];
        regVC.reguistBlock = ^(NSString *phstr, NSString *psstr) {
            self.phfield.text = phstr;
            self.psfield.text = psstr;
        };
        [self.navigationController pushViewController:regVC animated:YES];
    }
}


-(void)loginRequestMethod{
    NSString *endStr = [NSString stringWithFormat:@"/dashop/happuser/app/login.do?USERNAME=%@&PASSWORD=%@",self.phfield.text,self.psfield.text];
    NSString  *newUrlString = [endStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [MethodClass returnUrlSetStrWSDLURL:newUrlString];
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            if ([response[@"RESULT"] integerValue] == 1) {
                self.logBlock(response[@"APPUSER"]);
                NSDictionary *dic = response[@"APPUSER"];
                [UserDefault setObject:self.phfield.text forKey:LogUserName];
                [UserDefault setObject:self.psfield.text forKey:LogPassWord];
                [UserDefault setObject:dic[@"NAME"] forKey:LogRealName];
                [UserDefault setObject:dic[@"USER_ID"] forKey:LogUserID];
                
                NSString *urlstr = [NSString stringWithFormat:@"/dashop/%@",dic[@"SFID"]];
                NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
                [UserDefault setObject:endstr forKey:LogUserSFID];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self alerWithMessage:response[@"MESSAGE"]];
            }
            [UserDefault synchronize];
        }];
        
       
    } failBlock:^(NSError *error) {
        
    }];
}

//已经取消编辑状态 结束编辑
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([textField.placeholder isEqualToString:@"输入验证码"]) {
        if (![textField.text isEqualToString:self.yzmStr]) {
            [self alerWithMessage:@"验证码不正确"];
            textField.text = @"";
        }
    }else if ([textField.placeholder isEqualToString:@"确认密码"]){
        if (![textField.text isEqualToString:self.psfield.text]) {
            [self alerWithMessage:@"密码不一致"];
            textField.text = @"";
        }
        
    }
    
}


//封装提示框方法
-(void)alerWithMessage:(NSString *)msg{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        //延迟1秒自动消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}


@end
